package com.config;

import java.util.Date;

import com.business.user.validator.UserValidator;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.model.User;

public class IndexController extends Controller{
	
	public void index() { 
		String keyword = (String) getSession().getAttribute("keyword");
		String sqloption = "SELECT `user`.id AS 'user.id',`user`.nick_name AS 'user.nickName', "
				+ "`user`.head_portrait_img AS 'user.headPortraitImg',"
				+ "`user`.user_level AS 'user.userLevel',"
				+ "`section`.`id` AS 'section.id',`section`.`name` AS 'section.name',"
				+ "`section`.remark AS 'section.remark',"
				+ "`section`.section_img AS 'section.sectionImg'";
		String sql = " FROM "
				+ "`user` INNER JOIN "
				+ "`section` ON(`section`.user_id = `user`.id) WHERE `section`.it_status<3 ";
		if(keyword!=null&&!"".equals(keyword.trim())){
			sql = sql +" AND `section`.context LIKE \"%"+keyword.trim()+"%\" OR `section`.name LIKE \"%"+keyword.trim()+"%\" ";
		}
		sql = sql + " ORDER BY `section`.id desc ";
		Page<Record> userAndSectionRecord = Db.paginate(getParaToInt(0,1), 5,sqloption, sql);
		setAttr("sectionPage",userAndSectionRecord);
        render("/index.html");  
    }
	//登录页面
	public void login(){
		render("/web/user/login.html");
	}
	
	//登出页面
	@Clear
	public void loginout(){
		try{
			User user = User.dao.findById(((User)getSession().getAttribute("user")).getId());
			user.setLastLoginTime(new Date());
			user.update();
			getSession().removeAttribute("user");
		}catch (Exception e) {
			e.printStackTrace();
		}
		redirect("/");
	}
	
	//发帖
	public void addSection(){
		render("/web/section/add.html");
	}
	
	//修改个人信息页面
	@Before(UserValidator.class)
	public void modify(){
		render("/web/user/modify.html");
	}
	public void register(){
		render("/web/user/register.html");
	}
	
	public void findKeyWork(){
		try{
			String keyWord = getPara("_commtop_keyword");
			String url = getPara("_commtop_url");
			if(keyWord==null||"".equals(keyWord.trim())){
				getSession().removeAttribute("keyword");
			}else{
				getSession().setAttribute("keyword", keyWord);
			}
			if(url!=null&&!"".equals(url)){
				redirect(url);
				return;
			}else{
				redirect("/");
				return;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
		
	
}
